package com.my.lock.v26;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by ZhongGang
 * at 2018/9/17 18:01
 */
public class SpinLock {
    private static final Logger LOGGER = LoggerFactory.getLogger(SpinLock.class);

    private AtomicBoolean locked = new AtomicBoolean(false);

    public void lock() {
        while (!this.locked.compareAndSet(false, true)) {
            //spin here
        }
        LOGGER.info("locked by {}", Thread.currentThread().getName());
    }

    public void unlock() {
        this.locked.set(false);
    }

    public static void main(String[] args) {
        SpinLock lock = new SpinLock();

        for (int i = 0; i < 3; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        lock.lock();

                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        throw new UnsupportedOperationException("Not yet implemented!");
                    } finally {
                        lock.unlock();
                    }
                }
            }).start();
        }
    }
}
